<template>
  <div class="wang-editor">
    <Toolbar
      style="border-bottom: 1px solid #dcdfe6"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="newValueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onBlur="handleBlur"
    />
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { DomEditor, i18nChangeLanguage } from '@wangeditor/editor'
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()

watch(
  locale,
  (val) => {
    i18nChangeLanguage(val) // 'en' 或 'zh-CN'
  },
  {
    immediate: true
  }
)

const props = defineProps({
  valueHtml: {
    type: String,
    required: true,
    default: ''
  },
  mode: {
    type: String,
    default: 'simple' // 可选值：[default | simple]
  },
  placeholder: {
    type: String,
    default: ''
  },
  style: {
    type: String,
    default: 'min-height: 300px;'
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const newValueHtml = ref('')
watch(
  () => props.valueHtml,
  () => {
    newValueHtml.value = JSON.parse(JSON.stringify(props.valueHtml))
  }
)

const toolbarConfig = {
  excludeKeys: ['header3', 'codeBlock', 'group-image', 'group-video', 'insertVideo']
}
const editorConfig = {
  placeholder: props.placeholder,
  readOnly: props.readOnly
  // MENU_CONF: {
  //   uploadImage: {
  //     server: '',
  //     fieldName: 'file',
  //     // 自定义插入图片
  //     customInsert(res, insertFn) {
  //       // res 即服务端的返回结果
  //       // 从 res 中找到 url alt href ，然后插图图片
  //       let url = `${globalUrl.url}${res.data.realPath}`
  //       insertFn(url, res.data.filename, '')
  //     }
  //   }
  // }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  // console.log(editor.getAllMenuKeys())

  editor.on('fullScreen', () => {
    ElMessage({
      type: 'info',
      message: t('fullScreenMsg'),
      offset: 60,
      duration: 2000
    })
  })
}

const handleBlur = () => {
  const editor = editorRef.value
  const toolbar = DomEditor.getToolbar(editor)
  // console.log(toolbar.getConfig())
}

// 获取富文本内容
const getValueHtml = () => {
  return editorRef.value.getHtml()
}

// 获取富文本内容
const getIsEmpty = () => {
  return editorRef.value.isEmpty()
}

defineExpose({
  getValueHtml,
  getIsEmpty
})
</script>

<style scoped lang="scss">
.wang-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
}

.w-e-full-screen-container {
  z-index: 999;
}
</style>
